using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

namespace Voodoo.Meta.RVModules
{
	public class RVLoadingSprite : MonoBehaviour
	{
		public Sprite loadingSprite;

		public Image defaultImage;

		public Button buttonRV;

		public bool handleInteractivity;

		private Sprite _defaultSprite;

		private Color _defaultColor;

		private bool _subscribed;

		private CancellationTokenSource _cancellationTokenSource;

		private void Start()
		{
			if (buttonRV == null)
			{
				buttonRV = GetComponent<Button>();
			}
			if (defaultImage == null)
			{
				defaultImage = GetComponent<Image>();
			}
			if (buttonRV != null)
			{
				buttonRV.onClick.AddListener(PrepareCheckRV);
			}
		}

		private void OnEnable()
		{
			PrepareCheckRV();
		}

		private void PrepareCheckRV()
		{
			PrepareCheckRVAsync();
		}

		private async Task PrepareCheckRVAsync()
		{
			_cancellationTokenSource?.Cancel();
			if (defaultImage != null)
			{
				if (_defaultSprite == null)
				{
					_defaultSprite = defaultImage.sprite;
					_defaultColor = defaultImage.color;
				}
				defaultImage.transform.localRotation = Quaternion.identity;
			}
			if (handleInteractivity && buttonRV != null)
			{
				buttonRV.interactable = false;
			}
			_cancellationTokenSource = new CancellationTokenSource();
			await Task.Delay(TimeSpan.FromSeconds(0.10000000149011612), _cancellationTokenSource.Token);
			DoCheckRV();
		}

		private void DoCheckRV()
		{
			OnRVReady(success: true);
		}

		private async Task RotateInfinite(Vector3 rotation, float duration)
		{
			while (!_cancellationTokenSource.IsCancellationRequested)
			{
				await Rotate(rotation, duration);
			}
		}

		private async Task Rotate(Vector3 rotation, float duration)
		{
			float timeElapsed = 0f;
			while (timeElapsed < duration && !_cancellationTokenSource.IsCancellationRequested)
			{
				Vector3 currentRotation = Vector3.Lerp(Vector3.zero, rotation, timeElapsed / duration);
				await Task.Yield();
				timeElapsed += Time.deltaTime;
				Vector3 vector = Vector3.Lerp(Vector3.zero, rotation, timeElapsed / duration);
				defaultImage.transform.Rotate(vector - currentRotation, Space.Self);
			}
			if (this != null)
			{
				defaultImage.transform.localRotation = Quaternion.identity;
			}
		}

		private void OnDisable()
		{
			_cancellationTokenSource?.Cancel();
		}

		private void OnRVReady(bool success)
		{
			_subscribed = false;
			if (success)
			{
				if (handleInteractivity && buttonRV != null)
				{
					buttonRV.interactable = true;
				}
				if (defaultImage != null)
				{
					defaultImage.sprite = _defaultSprite;
					defaultImage.color = _defaultColor;
					defaultImage.transform.localRotation = Quaternion.identity;
				}
				_cancellationTokenSource?.Cancel();
			}
		}
	}
}
